//
//  DropDownMenuCell.swift
//  DropDownMenu
//
//  Created by 在成长开发 on 2024/6/24.
//  Copyright © 2024 刘爽. All rights reserved.
//

import UIKit

public enum MenuType {
    case title
    case leftImage
    case rightImage
}

public class DropDownMenuCell: UICollectionViewCell {
    var titleLabel: UILabel = {
        let view = UILabel()

        view.textAlignment = .left
        view.textColor = .black
        view.font = .systemFont(ofSize: 14)
        view.lineBreakMode = .byTruncatingTail

        return view
    }()

    var iconImage: UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFill
        return view
    }()

    var menuType: MenuType {
        didSet {
            switch menuType {
            case .title:
                contentView.addSubview(titleLabel)
                iconImage.removeFromSuperview()
            case .leftImage:
                contentView.addSubview(titleLabel)
                contentView.addSubview(iconImage)
            case .rightImage:
                contentView.addSubview(titleLabel)
                contentView.addSubview(iconImage)
            }
        }
    }

    var contentLeft: CGFloat = 0
    var contentRight: CGFloat = 0
    var textImageSpace: CGFloat = 8

    override public init(frame: CGRect) {
        self.menuType = .title
        super.init(frame: frame)

        self.backgroundView = UIView()

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    public override func layoutSubviews() {
        super.layoutSubviews()

        switch menuType {
        case .title:
            titleLabel.frame = CGRect(x: contentLeft, y: 0, width: CGRectGetWidth(self.bounds) - contentLeft - contentRight, height: CGRectGetHeight(self.bounds))
        case .leftImage:
            iconImage.frame = CGRectMake(contentLeft, (CGRectGetHeight(self.bounds) - (iconImage.image?.size.height ?? 0)) / 2, iconImage.image?.size.width ?? 0, iconImage.image?.size.height ?? 0)
            titleLabel.frame = CGRect(x: CGRectGetMaxX(iconImage.frame) + textImageSpace, y: 0, width: CGRectGetWidth(self.bounds) - CGRectGetMaxX(iconImage.frame) - textImageSpace - contentRight, height: CGRectGetHeight(self.bounds))
        case .rightImage:
            iconImage.frame = CGRect(x: CGRectGetWidth(self.bounds) - contentRight - (iconImage.image?.size.width ?? 0), y: (CGRectGetHeight(self.bounds) - (iconImage.image?.size.height ?? 0)) / 2, width: iconImage.image?.size.width ?? 0, height: iconImage.image?.size.height ?? 0)
            titleLabel.frame = CGRect(x: contentLeft, y: 0, width: CGRectGetWidth(self.bounds) - (CGRectGetWidth(iconImage.frame) != 0 ? textImageSpace : 0) - CGRectGetWidth(iconImage.frame) - contentRight, height: CGRectGetHeight(self.bounds))
        }
    }
}
